import { FuncService } from "@/services/func";
import { ActionType } from "@ant-design/pro-components";
import { message } from "antd";
import { useCallback, useRef } from "react"

export default ()=>{
  const actionRef = useRef<ActionType>();

  const getHandler = useCallback(async () => {
    return FuncService.getFuncList();
  }, []);

  const addHandler = useCallback(async (body: API.Func_Add_Body) => {
    const hide = message.loading('dismissing..');
    try {
      await FuncService.addFunc(body);
      hide();
      message.success(`新增成功！`);
      actionRef.current?.reload?.();
      return true;
    } catch (error) {
      hide();
      message.error(`新增失败，请重试！`);
      return false;
    }
  }, []);
  const updateHandler = useCallback(async (body: API.Func_Update_Body) => {
    const hide = message.loading('dismissing..');
    try {
      await FuncService.updateFunc(body);
      hide();
      message.success(`修改成功！`);
      actionRef.current?.reload?.();
      return true;
    } catch (error) {
      hide();
      message.error(`修改失败，请重试！`);
      return false;
    }
  }, []);
  const removeHandler = useCallback(async (id:number) => {
    const hide = message.loading('dismissing..');
    try {
      await FuncService.removeFunc(id);
      hide();
      message.success(`删除成功！`);
      actionRef.current?.reload?.();
      return true;
    } catch (error) {
      hide();
      message.error(`删除失败，请重试！`);
      return false;
    }
  }, []);

  //数组转树

  const arr2tree = (arr: Array<API.FuncInfo>): API.FuncInfo | null => {
    if (!Array.isArray(arr)) {
      throw new Error('我要一个数组');
    }
    function _arr2tree(fid: number): API.FuncInfo | null {
      let nodes = arr.filter((item) => item.func_fid === fid);
      if (nodes.length === 0) {
        return null;
      }
      return nodes.reduce((result: any, node: any) => {
        let newNode: any = { ...node };
        let children = _arr2tree(newNode.func_id);
        if (children) {
          newNode.children = children;
        }
        result.push(newNode);
        return result;
      }, []);
    }
    return _arr2tree(0);
  };

  return { actionRef, getHandler, addHandler, updateHandler,removeHandler, arr2tree };
}